#!/bin/bash

# AI Daily - 停止前后端服务脚本
echo "🛑 Stopping AI Daily Services..."

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m' # No Color

# 获取脚本所在目录
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BACKEND_DIR="$SCRIPT_DIR/backend"

# 函数：停止进程
stop_service() {
    local service_name=$1
    local pid_file=$2
    
    if [ -f "$pid_file" ]; then
        local pid=$(cat "$pid_file")
        if ps -p $pid > /dev/null 2>&1; then
            echo -e "${YELLOW}🔄 Stopping $service_name (PID: $pid)...${NC}"
            kill -TERM $pid
            sleep 2
            
            # 如果进程仍在运行，强制杀死
            if ps -p $pid > /dev/null 2>&1; then
                echo -e "${YELLOW}⚠️  Force killing $service_name...${NC}"
                kill -9 $pid
            fi
            
            echo -e "${GREEN}✅ $service_name stopped successfully${NC}"
        else
            echo -e "${YELLOW}⚠️  $service_name process not found (PID: $pid)${NC}"
        fi
        rm -f "$pid_file"
    else
        echo -e "${YELLOW}⚠️  $service_name PID file not found${NC}"
    fi
}

# 函数：杀死指定端口的所有进程
kill_port_processes() {
    local port=$1
    local service_name=$2
    
    local pids=$(lsof -ti :$port 2>/dev/null)
    if [ ! -z "$pids" ]; then
        echo -e "${YELLOW}🔄 Killing $service_name processes on port $port...${NC}"
        echo $pids | xargs kill -9
        echo -e "${GREEN}✅ $service_name processes stopped${NC}"
    else
        echo -e "${BLUE}ℹ️  No $service_name processes found on port $port${NC}"
    fi
}

# 停止后端服务
echo -e "${BLUE}🔧 Stopping Backend Service...${NC}"
stop_service "Backend" "$BACKEND_DIR/backend.pid"

# 停止前端服务
echo -e "${BLUE}🔧 Stopping Frontend Service...${NC}"
stop_service "Frontend" "$SCRIPT_DIR/frontend.pid"

# 确保端口被清理
echo -e "${BLUE}🧹 Cleaning up ports...${NC}"
kill_port_processes 8001 "Backend"
kill_port_processes 3000 "Frontend"

# 清理日志文件（可选）
read -p "Do you want to clear log files? (y/n): " -n 1 -r
echo
if [[ $REPLY =~ ^[Yy]$ ]]; then
    if [ -f "$BACKEND_DIR/backend.log" ]; then
        > "$BACKEND_DIR/backend.log"
        echo -e "${GREEN}✅ Backend log cleared${NC}"
    fi
    
    if [ -f "$SCRIPT_DIR/frontend.log" ]; then
        > "$SCRIPT_DIR/frontend.log"
        echo -e "${GREEN}✅ Frontend log cleared${NC}"
    fi
fi

echo ""
echo -e "${GREEN}🎉 All services stopped successfully!${NC}"
echo -e "${BLUE}💡 Use ${GREEN}./start_services.sh${NC} to start services again${NC}"